﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace CardPlay.Client.Behaviors
{
    public class KeyGestureTrigger : TriggerBase<FrameworkElement>
    {
        public static readonly DependencyProperty KeyProperty = DependencyProperty.Register("Key",
            typeof(Key), typeof(KeyGestureTrigger), new PropertyMetadata(Key.None));

        public static readonly DependencyProperty ModifiersProperty = DependencyProperty.Register("Modifiers",
            typeof(ModifierKeys), typeof(KeyGestureTrigger), new PropertyMetadata(ModifierKeys.None));

        public Key Key
        {
            get { return (Key) GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }

        public ModifierKeys Modifiers
        {
            get { return (ModifierKeys)GetValue(ModifiersProperty); }
            set { SetValue(ModifiersProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.KeyUp += OnKeyUp;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.KeyUp -= OnKeyUp;
        }

        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key || (Keyboard.Modifiers & Modifiers) != Modifiers) return;
            InvokeActions(null);
        }
    }
}